package com.crm.aspect;

import com.alibaba.fastjson.JSON;
import com.crm.common.annotation.Log;
import com.crm.common.enums.BusinessStatus;
import com.crm.common.utils.AddressUtils;
import com.crm.common.utils.IpUtils;
import com.crm.common.utils.StringUtils;
import com.crm.common.utils.UserThreadLocal;
import com.crm.domain.SysOperLog;
import com.crm.domain.User;
import com.crm.mapper.UserMapper;
import com.crm.service.OperLogService;
import com.crm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class OperLogAspect {
    @Autowired
    private OperLogService operLogService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 配置织入点 - 使用@Log注解的方法
     */
    @Pointcut("@annotation(com.crm.common.annotation.Log)")
    public void logPointCut() {
    }
    
    /**
     * 处理完请求后执行
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }
    
    /**
     * 拦截异常操作
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }
    
    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }
            
            // 获取当前用户
            Long userId = UserThreadLocal.getUserId();
            if (userId == null) {
                log.error("获取当前用户id为空");
                return;
            }
            log.info("打印当前用户id：{}",userId);
            User loginUser = userMapper.selectById(userId);
            
            // 创建操作日志对象
            SysOperLog operLog = new SysOperLog();
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            
            // 请求的地址
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            operLog.setOperIp(IpUtils.getIpAddr(request));
            operLog.setOperUrl(request.getRequestURI());
            operLog.setRequestMethod(request.getMethod());
            
            // 设置操作人
            if (loginUser != null) {
                operLog.setOperName(loginUser.getUserName());
                operLog.setDeptName(loginUser.getDeptName());
            }

            
            // 设置操作地点
            operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
            
            // 设置操作时间
            operLog.setOperTime(LocalDateTime.now());
            
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            
            // 处理设置注解上的参数
            getControllerMethodDescription(controllerLog, operLog);
            
            // 是否需要保存request，参数和值
            if (controllerLog.isSaveRequestData()) {
                setRequestValue(joinPoint, operLog);
            }
            
            // 是否需要保存response，参数和值
            if (controllerLog.isSaveResponseData() && jsonResult != null) {
                operLog.setJsonResult(JSON.toJSONString(jsonResult));
            }
            
            // 如果有异常，记录异常信息
            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            
            // 保存数据库
            operLogService.insertOperlog(operLog);
        } catch (Exception exp) {
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }
    
    /**
     * 获取注解中对方法的描述信息
     */
    private void getControllerMethodDescription(Log log, SysOperLog operLog) {
        // 设置action动作
        operLog.setBusinessType(log.businessType().getCode());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType().getCode());
    }
    
    /**
     * 获取请求的参数，放到log中
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) {
        try {
            String params = argsArrayToString(joinPoint.getArgs());
            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
        } catch (Exception e) {
            log.error("获取请求参数异常", e);
        }
    }
    
    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }
    
    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (o != null && !isFilterObject(o)) {
                    try {
                        params.append(JSON.toJSONString(o)).append(" ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return params.toString().trim();
    }
    
    /**
     * 判断是否需要过滤的对象
     */
    private boolean isFilterObject(final Object o) {
        return o instanceof MultipartFile || o instanceof HttpServletRequest
                || o instanceof HttpServletResponse || o instanceof BindingResult;
    }
}